#coding=utf-8
from flask import Flask, render_template,url_for,jsonify,request,json
from werkzeug.utils import secure_filename


app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World'


@app.route('/user/<name>')
def username(name):
    #通过数据库查询
    #通过数据库修改
    #其他业务操作
    #修改相关信息，反馈到前台
    if(name == "张三"):
        name="真是张三"
    else:
        name="不是张三，而是"+name
    return '<h1>hello,%s</h1>' % name

@app.route('/user')
def user():
    users=[['张三','男','重庆'],
          ['李四','女','四川']]
    return render_template("user.html",list=users)

@app.route('/url')
def redirect_to_url():
    return url_for('post_show',post_id=666)

@app.route('/post/<int:post_id>')
def post_show(post_id):
    return 'Post ID:%d' % post_id

@app.route('/getJson')
def getJson():
    data={
        "name":"张三",
        "sex":"男",
        "age":20,
        "address":"666666"
    }
    #将数据转Json，这个数据可以是任何
    return jsonify(data)

#Get传参
@app.route('/login',methods=['GET','POST','PUT'])
def login():
    data="无数据"
    if request.method == 'GET':
        print("当前请求方法是GET")
        username=request.args.get("username")
        address=request.values.get("address")

        data={
            "username":username,
            "address":address
        }

    elif request.method == "POST":
        print("当前请求方法是POST")
        username = request.args.get("username")
        address = request.values.get("address")

        data = {
            "username": username,
            "address": address
        }

    elif request.method == "PUT":
        print("当前请求方法是PUT")
        username = request.args.get("username")
        address = request.values.get("address")

        data = {
            "username": username,
            "address": address
        }
    print(data)
    return jsonify(data)

#传递json
@app.route('/passJson',methods=['POST'])
def passJson():
    data = json.loads(request.get_data(as_text=True))
    return jsonify(data)

#上传文件
#步骤1，创建路由，创一个到静态文件的路由
@app.route('/upload/index')
def toUploadPage():
    return render_template('upload.html')

#步骤2，静态文件中有文件上传功能，点击该功能上传文件
@app.route('/upload',methods=['POST'])
def upload():
    if request.method == 'POST':
        file=request.files['file']
        print(request.files)

        file.save(secure_filename(file.filename))
        return "文件上传成功！"
    else:
        return render_template('upload.html')

if __name__ == '__main__':
    app.debug=True
    app.run()